# -*- coding: utf-8 -*-
import json
import re
import logging
from common.cache import redis_cache
from common.cache.redis_cache import get_available_withdraw_channels
from common.stats import MG_BIGBANG_COLL as mg
from common.transaction.model import *
from common.account.db.account import get_account
from common.transaction.model import WITHDRAW_TYPE
from common.utils import tz
from common.utils.bot import send_text_msg
from common.black_account.db import get_withdraw_black_list
from common.black_account.model import WITHDRAW_BLACK_TYPE
from common.transaction.db import withdraw_back

_LOGGER = logging.getLogger('alipay')

GROUP_ID = 4335

_SYSTEM_ADMIN_ID = -1


def notify_balance(payer):
    try:
        payer_no = payer['no']
        payer_name = payer['payer']
        current_status = redis_cache.get_withdraw_status(payer_no)
        if not current_status or 0 == int(current_status):
            send_text_msg(3, GROUP_ID, u'cp兑换余额不足,{}{}'.format(
                payer_name, payer_no))
            _LOGGER.info('notify_balance succ')
            redis_cache.set_withdraw_status(payer_no, 1)
    except Exception as e:
        _LOGGER.exception('notify_balance errir, %s', e)


def check_daily_risk(amount):
    interval_price = 100000
    before_price = redis_cache.get_withdraw_daily_amount()
    after_price = redis_cache.add_withdraw_daily_amount(amount)
    if after_price / interval_price > before_price / interval_price:
        # notify
        try:
            send_text_msg(3, GROUP_ID, u'cp今日兑换已超过{}'.format(after_price))
            _LOGGER.warn('check_daily_risk, sms notified, current amount %s', after_price)
        except Exception as e:
            _LOGGER.exception('check_daily_risk, sms notify error, %s', e)


def check_user_risk(uid, item):
    reason_list = []
    account = get_account(uid)
    trans_info = json.loads(item.extend)
    if item.target_type == WITHDRAW_TYPE.ALIPAY:
        trans_no = trans_info['info']['zfb'].lower()
        trans_name = trans_info['info']['name'].encode('utf-8')
        account_key = 'black_alipayno'
    else:
        trans_no = trans_info['info']['no']
        trans_name = trans_info['info']['name'].encode('utf-8')
        try:
            if not str(trans_no).isdigit():
                return False, ['invalid_bankcard']
        except Exception as e:
            return False, ['invalid_bankcard']
        account_key = 'black_bank'
    black_dct = get_withdraw_black_list()
    for key, black_list in black_dct.iteritems():
        if "test_uid" == key and str(uid) in black_list:
            reason_list.append(u"测试id黑名单")
        elif "black_uid" == key and str(uid) in black_list:
            reason_list.append(u'恶意用户id黑名单')
        elif WITHDRAW_BLACK_TYPE.BLACK_SALES == key and str(uid) in black_list:
            reason_list.append(u'电销黑名单')
        elif WITHDRAW_BLACK_TYPE.BLACK_OPERATIONS == key and str(uid) in black_list:
            reason_list.append(u'运营黑名单')
        elif key == account_key and str(trans_no) in black_list:
            reason_list.append(u'黑名单收款账户')
        elif "black_name" == key and trans_name in black_list:
            reason_list.append(u'黑名单收款姓名')
    if account.is_virtual:
        reason_list.append(u"virtual account")
    if account.status == 1024:
        reason_list.append(u'非法用户')
    user_stats = mg.user_stats.find_one({'_id': uid})
    total_recharge = 0
    if not user_stats:
        reason_list.append(u'不存在累积数据')
    else:
        total_profit = user_stats.get('gain', {}).get('total', 0) + \
                       user_stats.get('kfc', {}).get('gain_amount', 0) + \
                       user_stats.get('lottery', {}).get('gain_amount', 0) + \
                       user_stats.get('fruit', {}).get('gain_amount', 0) + \
                       user_stats.get('bull', {}).get('gain_amount', 0)
        if len(reason_list) == 0 and total_profit < 0:
            return True, 'success'
        if user_stats.get('withdraw', {}).get('total', 0) == 0:
            reason_list.append(u'用户首次提现')
        if user_stats.get('recharge', {}).get('applepay', 0) > 0:
            reason_list.append(u'apple pay用户')
        total_recharge = user_stats.get('recharge', {}).get('total', 0)
        total_withdraw = user_stats.get('withdraw', {}).get('total', 0)
        if total_recharge == 0:
            reason_list.append(u'没有充值')
        else:
            if float(total_withdraw) / total_recharge >= 3:
                reason_list.append(u'累积提现{}/累积充值{}>=3'.format(total_withdraw,
                                                              total_recharge))
        print total_profit
        print total_profit >= 20000
        if total_recharge and float(total_profit) / total_recharge >= 3:
            reason_list.append(u'盈利总额{}/累积充值{}>=3'.format(total_profit, total_recharge))
        if total_withdraw - total_recharge - float(account.balance) >= 20000:
            reason_list.append(u'累计提现{}-累积充值{}-余额{}>=20000'.format(
                total_withdraw, total_recharge, account.balance))
        if float(total_profit) >= 20000:
            reason_list.append(u'累计产品玩法用户盈利{}超过20000'.format(total_profit))

    date_str = tz.local_now().strftime('%Y-%m-%d')
    daily_stats = mg.daily_stats.find_one({"_id": "%s-%s" % (uid, date_str)}) or {}
    if not daily_stats:
        reason_list.append(u'不存在今日数据')
    else:
        today_gain = daily_stats.get('total_gain', None)
        daily_withdraw = daily_stats.get('withdraw', {}).get('total', 0)
        if today_gain is None:
            reason_list.append(u'今日盈利数据缺失')
        elif float(today_gain) >= 10000:
            reason_list.append(u'今日盈利%s超过限额' % today_gain)
        dwc_total_profit = (daily_stats.get('kfc', {}).get('gain_amount', 0) +
                            daily_stats.get('lottery', {}).get('gain_amount', 0) +
                            daily_stats.get('fruit', {}).get('gain_amount', 0) +
                            daily_stats.get('bull', {}).get('gain_amount', 0))
        caipiao_total_profit = daily_stats.get('gain', {}).get('total', 0)
        total_profit = dwc_total_profit + caipiao_total_profit
        if total_profit >= total_recharge * 2:
            reason_list.append(u'当日产品玩法用户盈利超过充值金额2倍')
        if total_profit >= 5000:
            reason_list.append(u'当日产品玩法用户盈利{}超过5000'.format(total_profit))
        if daily_withdraw - total_profit >= 5000:
                reason_list.append(u'今日提现{}-今日用户盈利{}>5000'.format(daily_withdraw, total_profit))
    if item.price >= 5000:
        reason_list.append(u'当前提现金额{}超限'.format(item.price))
    withdraw_daily_stats = mg.withdraw_daily_stats.find_one({
        'day': date_str,
        'type': item.target_type,
        'no': trans_no
    }) or {}
    today_amount = withdraw_daily_stats.get('amount', 0)
    if today_amount >= 50000:
        reason_list.append(u'收款账号今日提现{}超过5w'.format(today_amount))
    today_user_id_count = 0
    for withdraw_stats in mg.withdraw_daily_stats.find({'day': date_str, 'user_id': uid}):
        today_user_id_count += int(withdraw_stats.get('count', 0))
    if len(reason_list) > 0:
        return False, reason_list
    return True, 'success'


def get_available_withdraw_type():
    channels = get_available_withdraw_channels()
    available_withdraw_types = []
    for channel in channels:
        if channel in [WITHDRAW_CHANNELS.JUSTPAY_ALIPAY, WITHDRAW_CHANNELS.GROUP_ALIPAY]:
            available_withdraw_types.append(WITHDRAW_TYPE.ALIPAY)
        if channel in [WITHDRAW_CHANNELS.UNIONAGENCY_BANKCARD]:
            available_withdraw_types.append(WITHDRAW_TYPE.BANKCARD)
    return available_withdraw_types
